package 多线程.多线程;

//线程安全问题
public class ThreadSafe {
    private static class Count{
        int size = 0;
        int num = 0;
        void add(){
            size++;
        }
        void adds(){
            num++;
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Count count = new Count();
        Thread t1 = new Thread(() ->{
            for (int i = 0; i < 5000; i++) {
                count.add();
            }
        });
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    count.add();
                }
            }
        });
        t1.start();
        t2.start();
        //t1,t2并发执行，并发性导致了运行结果和串行运行结果的不一致，导致线程不安全。
        t1.join();
        t2.join();
        Thread t3 = new Thread(() ->{
            for (int i = 0; i < 5000; i++) {
                count.adds();
            }
        });
        Thread t4 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 5000; i++) {
                    count.adds();
                }
            }
        });
        //t1,t2串行执行，
        t3.start();
        t3.join();
        t4.start();
        t4.join();
        System.out.println("并发执行结果:"+count.size);
        System.out.println("并发执行结果:"+count.num);
    }
}
